/*****
    -- mychattool.h
    functions for my chatroom.

    author:  blackay03
    time:    2017.11.16
    version: 1.3
 */

 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <strings.h>
 #include <errno.h>
 #include <sys/socket.h>
 #include <arpa/inet.h>
 #include <netinet/in.h>
 #include <sys/types.h>
 #include <unistd.h>

 #include <stddef.h>
 #include <time.h>

#ifndef   __MYCHATTOOL_H__
#define   __MYCHATTOOL_H__

#define BUFLEN 100
#define SERVER_PORT 155322
#define FILE_NAME_MAX_SIZE 512
#define BUFFER_SIZE 1024

void print_time(time_t timer ,struct tm *tblock){
    timer = time(NULL);
    tblock = localtime(&timer);
    printf("%s", asctime(tblock));
}

void p_emo(char array[]){
    int i=0;
    for(i=0;i<3;i++){
        printf("%c",array[i]);
    }
}

void emo_out(char buf[BUFLEN]){
    int i=1;
    char emoji_1[3] = ">_<";
    char emoji_2[3] = "-_-";
    char emoji_3[3] = "QAQ";
    //printf("%s\t",buf);
    //printf("%s\t",emoji_1);
    //printf("%s\t",emoji_2);
    //printf("%s\t",emoji_3);
    /*
    for(i = 1; i ;){
        if(!strncasecmp(buf,"emo1",4)){
            printf(" %s",emoji_1);
            break;
        }
        else if(!strncasecmp(buf,"emo2",4)){
            printf(" %s",emoji_2);
            break;
        }
        else if(!strncasecmp(buf,"emo3",4)){
            printf(" %s",emoji_3);
            break;
        }
        else break;
    }
*/
if(!strcmp(buf,"emo1")){
    p_emo(emoji_1);
    }
if(!strcmp(buf,"emo2")){
    p_emo(emoji_2);
    }
if(!strcmp(buf,"emo3")){
    p_emo(emoji_3);
    }
}

void file_get(char buffer[BUFLEN]){
    // 然后从buffer(缓冲区)拷贝到file_name中
        char file_name[FILE_NAME_MAX_SIZE+1];
        bzero(file_name, FILE_NAME_MAX_SIZE+1);
        strncpy(file_name, buffer, strlen(buffer)>FILE_NAME_MAX_SIZE?FILE_NAME_MAX_SIZE:strlen(buffer));
        printf("%s\n", file_name);

    // 打开文件，准备写入
        FILE *fp = fopen(file_name, "w");
        if(NULL == fp)
        {
            printf("File:\t%s Can Not Open To Write\n", file_name);
            exit(1);
        }

    // 从客户端接收数据到buffer中
        // 每接收一段数据，便将其写入文件中，循环直到文件接收完并写完为止
        bzero(buffer, BUFFER_SIZE);
        int length = 0;
        while((length = recv(new_server_socket_fd, buffer, BUFFER_SIZE, 0)) > 0)
        {
        if(strcmp(buffer,"OK")==0) break;
            if(fwrite(buffer, sizeof(char), length, fp) < length)
            {
                printf("File:\t%s Write Failed\n", file_name);
                break;
            }
            bzero(buffer, BUFFER_SIZE);
        }


    // 接收成功后，关闭文件
        printf("Receive File:\t%s From Client IP Successful!\n", file_name);
        fclose(fp);
}

#endif
